package com.shopping.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.shopping.commons.response.DataGradResp;
import com.shopping.commons.response.MessageResp;
import com.shopping.commons.service.CookieService;
import com.shopping.commons.util.CommonCode;
import com.shopping.commons.util.JsonUtil;
import com.shopping.mapper.CommodityMapper;
import com.shopping.mapper.ShopCarMapper;
import com.shopping.model.ShopCar;
import com.shopping.param.ShopCarParam;
import com.shopping.response.ShopCarResp;
import com.shopping.response.UserResp;
import com.shopping.service.IShopCarService;

@Service
public class ShopCarService implements IShopCarService{

	@Autowired
	private ShopCarMapper shopCarMapper;
	
	@Autowired
	private CommodityMapper commodityMapper;
	
	private SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	public MessageResp insert(ShopCar param) {
		MessageResp resp=new MessageResp();
		//TODO:   这里要对param进行一次加工，添加诸如  addrid    updateperson updatetime  delflag 
		//status     这样的一些参数
		Random r=new Random();
		param.setShopcid(r.nextInt(10000)+100000);//   100000-199999  之间的随机数
		param.setDelflag(CommonCode.DELFLAG_NORMAL);
		param.setCreatedate(sdf.format(new Date()));
		if(shopCarMapper.insertSelective(param)>0){
			//成功了
			resp.setCode("0000");
			resp.setMsg("添加成功");
		}else{
			resp.setCode("9999");
			resp.setMsg("添加失败");
		}
		return resp;
	}

	public MessageResp update(ShopCar param) {
		MessageResp resp=new MessageResp();
		ShopCar entity=shopCarMapper.selectByPrimaryKey(param.getShopcid());
		if(entity==null){
			//没找到
			resp.setCode("9999");
			resp.setMsg("未找到修改项");
			return resp;
		}
//		entity.setDelflag("1");
//		entity.setUpdatedate(sdf.format(new Date()));
		entity.setCommid(param.getCommid());
		entity.setDelflag(param.getDelflag()==null?CommonCode.DELFLAG_NORMAL:param.getDelflag());
		entity.setStatus(param.getStatus()==null?CommonCode.STATUS_ONE:param.getStatus());
		entity.setCommnum(param.getCommnum());
		entity.setUserid(param.getUserid());
		
		//自动更新   更新的时间  和更新的人
		entity.setUpdatedate(sdf.format(new Date()));
//		if(addressMapper.updateByPrimaryKey(param)>0){  hH会更新掉所有的字段，没有值的就用null覆盖
		if(shopCarMapper.updateByPrimaryKeySelective(entity)>0){
			//成功了
			resp.setCode("0000");
			resp.setMsg("修改成功");
		}else{
			resp.setCode("9999");
			resp.setMsg("修改失败");
		}
		return resp;
	}

	public MessageResp delete(Integer id) {
	//  在实现类中写的任何   与 接口无关的方法，都是在Controller中 不可见的
		MessageResp resp=new MessageResp();
			//TODO:如果没有这个id怎么办
			ShopCar entity=shopCarMapper.selectByPrimaryKey(id);
			if(entity==null){
				//没找到
				resp.setCode("9999");
				resp.setMsg("未找到删除项");
				return resp;
			}
			entity.setDelflag(CommonCode.DELFLAG_DELETE);
			entity.setUpdatedate(sdf.format(new Date()));//asf.pares("2015-10-10 10:10:10")
//			try {
//				Integer.parseInt("1asdfa");
//			} catch (NumberFormatException e) {
//				e.printStackTrace();
//			}
			if(shopCarMapper.updateByPrimaryKeySelective(entity)>0){
				//成功了
				resp.setCode("0000");
				resp.setMsg("删除成功");
			}else{
				resp.setCode("9999");
				resp.setMsg("删除失败");
			}
			return resp;
	}

	public DataGradResp<ShopCar> select(ShopCarParam param) {
		DataGradResp<ShopCar> resp=new DataGradResp<ShopCar>();
		//查询     可能有多个，可能是单个
		//如果前端没有传任何参数的话，delflag也要特殊处理下
		param.setDelflag(param.getDelflag()==null?"0":param.getDelflag());
		List<ShopCar> shopCarList;
		try {
			shopCarList = shopCarMapper.select(param);
		} catch (Exception e) {
			e.printStackTrace();
			resp.setCode("9999");
			resp.setMsg("查询失败");
			return resp;
		}
		resp.setCode("0000");
		resp.setMsg("查询成功");
		resp.setRows(shopCarList);
		resp.setTotal(shopCarMapper.count(CommonCode.DELFLAG_NORMAL));
		//resp.setObj(shopCarList);
		return resp;
	}

	public DataGradResp<ShopCar> select(ShopCar param) {
		// TODO Auto-generated method stub
		return null;
	}

	public MessageResp batchDelete(String ids) {
		// TODO Auto-generated method stub
		return null;
	}

	public MessageResp add(HttpServletResponse response,HttpServletRequest request, UserResp user, Integer commid) {
		MessageResp resp=new MessageResp();
		if(user==null){
			//未登录，存cookie
			Cookie c=CookieService.getCookieByName(request, "shopCar");
			Map<String,Integer> shopCarMap=null;
			if(c==null||StringUtils.isEmpty(c.getValue())){
				//创建一个新的cookie
				shopCarMap=new HashMap<String,Integer>();
				shopCarMap.put(commid+"", 1);
			}else{
				shopCarMap=JsonUtil.jsonToObject(c.getValue(), Map.class);
				Object numObj=shopCarMap.get(commid+"");
				if(numObj==null){
					//put一个新的
					shopCarMap.put(commid+"",1);
				}else{
					shopCarMap.put(commid+"",Integer.parseInt(numObj.toString())+1);
				}
			}
			CookieService.addCookie(response, "shopCar", JsonUtil.mapTOString(shopCarMap), 60*60*24*7);
		}else{
			//登陆，存数据库
			ShopCar param=new ShopCar();
			Random r=new Random();
			param.setCommid(commid);
			param.setDelflag(CommonCode.DELFLAG_NORMAL);
			List<ShopCar> retList=shopCarMapper.select(param);
			if(retList!=null&&!retList.isEmpty()){
				param=retList.get(0);
				param.setCommnum(param.getCommnum()+1);
				param.setUpdatedate(sdf.format(new Date()));
				if(shopCarMapper.updateByPrimaryKeySelective(param)<0){
					resp.setCode(CommonCode.FAIL);
					resp.setMsg("添加购物车失败");
					return resp;
				}
			}else{
				param.setShopcid(r.nextInt(1000)+10000);
				param.setStatus(CommonCode.STATUS_ONE);
				param.setCommid(commid);
				param.setCommnum(1);
				param.setUserid(user.getUserid());
				param.setCreatedate(sdf.format(new Date()));
				if(shopCarMapper.insertSelective(param)<0){
					resp.setCode(CommonCode.FAIL);
					resp.setMsg("添加购物车失败");
					return resp;
				}
			}
		}
		resp.setCode(CommonCode.SUCCESS);
		resp.setMsg("添加购物车成功");
		return resp;
	}

	public ModelAndView toShopCar(HttpServletRequest request,HttpServletResponse response, UserResp user) {
		ModelAndView mv=new ModelAndView("views/front/shopCar");
		if(user==null){
			//从cookie取
			Cookie c=CookieService.getCookieByName(request, "shopCar");
			if(c!=null){
				Map<String,Integer> shopCarMap=JsonUtil.jsonToObject(c.getValue(), Map.class);
				List<ShopCarResp> retList=new ArrayList<ShopCarResp>();
				if(shopCarMap!=null){
					for(Map.Entry<String, Integer> entry : shopCarMap.entrySet()){
						Integer commid=Integer.parseInt(entry.getKey().toString());
						Integer num=entry.getValue();
						ShopCarResp shopCarItem=new ShopCarResp();
						shopCarItem.setCommodityObj(commodityMapper.selectByPrimaryKey(commid));
						shopCarItem.setCommnum(num);
						retList.add(shopCarItem);
					}
				}
				mv.addObject("shopCar",retList);
			}
		}else{
			//从数据库取
			mv.addObject("shopCar",shopCarMapper.selectIncludcommodity(user.getUserid()));
		}
		return mv;
	}

	public Integer getCount(Integer userid) {
		return shopCarMapper.countByUserid();
	}
	
}
